#include "logger.h"
#include <log4cpp/Category.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/FileAppender.hh>
#include <log4cpp/RollingFileAppender.hh>
using namespace log4cpp;
//初始静态成员
Logger*Logger::_pInstance = nullptr;   

Logger::Logger()
:_root(Category::getInstance("multiAppender"))
{
    //创建OstreamAppender (输出到控制台,和文件)
    OstreamAppender *osAppender = new OstreamAppender("console",&cout);
    FileAppender *fileAppender = new FileAppender("file","test.log");
    RollingFileAppender *rollfileAppender = new RollingFileAppender("Rollingfile","roll.log",1024*1024,9);
   
    //创建PatternLayout(设置日志格式)
    PatternLayout* osPl = new PatternLayout();
    PatternLayout* filePl = new PatternLayout();
    PatternLayout* rollfilePl = new PatternLayout();

    osPl->setConversionPattern("%d %c [%p] %m%n");
    filePl->setConversionPattern("%d %c [%p] %m%n");
    rollfilePl->setConversionPattern("%d %c [%p] %m%n");

    osAppender->setLayout(osPl);
    fileAppender->setLayout(filePl);
    rollfileAppender->setLayout(rollfilePl);

    //获取根Category并配置
    _root.addAppender(osAppender);
    _root.addAppender(fileAppender);
    _root.addAppender(rollfileAppender);

    _root.setPriority(Priority::DEBUG);//调试级别
}

//清理log4cpp资源
Logger::~Logger(){
    Category::shutdown();
}

Logger* Logger::getInstance(){
    if(!_pInstance){
        _pInstance = new Logger();
    }
    return _pInstance;
}

void Logger::destroy(){
    if(_pInstance){
        delete _pInstance;
        _pInstance = nullptr;
    }
}

//日志输入实现
void Logger::warn(const char *file,int line,const char *func, const char *msg){
    _root.warn("[%s:%d (%s)] %s",file,line,func,msg);
}

void Logger::error(const char *file,int line,const char *func, const char *msg){
    _root.error("[%s:%d (%s)] %s",file,line,func,msg);
}

void Logger::debug(const char *file,int line,const char *func, const char *msg){
    _root.debug("[%s:%d (%s)] %s",file,line,func,msg);
}

void Logger::info(const char *file,int line,const char *func, const char *msg){
    _root.info("[%s:%d (%s)] %s",file,line,func,msg);
}
